package plug.bookmarks;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.JTree;
import javax.swing.ToolTipManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;

import com.mxcyk.serviceLogic.*;
import com.uujava.minibox.config.Config;
import com.uujava.minibox.ui.tree.MyTreeCellRenderer;
import com.uujava.minibox.ui.tree.ShowAppToolTip;
import com.uujava.minibox.ui.tree.TreeUI;

public class BookmarksTree extends JTree implements MouseListener,
		MouseMotionListener {
	private Logger logger=Logger.getLogger(BookmarksTree.class);

	private static final long serialVersionUID = -4990742335399141339L;

	DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
	 private Control control;//书签的C层
	public void setControl(Control control) {
		this.control = control;
	}

	Run run = Run.getRun();// 程序执行类
	
	final String strItemTitleAdd = "添加";
	final String strItemTitleDel = "刪除";
	final String strItemTitleRename = "重命名";
	final String strItemTitlMessagee = "屬性";
	// -------------JtoolIip-----------------------------------------------
	public ShowAppToolTip toolTip = new ShowAppToolTip();

	// -------------JtoolIip-----------------------------------------------

	/**
	 * 初始化Tree
	 * 
	 * @param root
	 *            传入捆绑好的Tree的root
	 */
	public BookmarksTree(DefaultMutableTreeNode root) {
		addMouseListener(this);
		ToolTipManager.sharedInstance().registerComponent(this);// 提示注册
		initMenu();// 初始化菜单
		this.setUI(new TreeUI());// 设置树的平行化
		this.setModel(new DefaultTreeModel(root));
		this.setRootVisible(false);// 隐藏根节点
		this.setToggleClickCount(1);// 展开节点之前的鼠标单击数

		MyTreeCellRenderer myCellRenderer = new MyTreeCellRenderer();
		// 设置叶子节点的图标
		this.setCellRenderer(myCellRenderer);

		this.addMouseMotionListener(this);
		// --------设置toolTip的背景图片-------------------------------------
		// toolTip.setPatch(getClass().getResource("/Skins/content_bg2.9.png"),
		// false);
	}

	/**
	 * 功能：为groupNode组添加节点
	 * 
	 * @param groupNode
	 *            组
	 * @param node
	 *            要添加的节点
	 */
	// public void addNode(DefaultMutableTreeNode
	// groupNode,DefaultMutableTreeNode node){
	//		
	// groupNode.add(node);
	// }
	public JToolTip createToolTip() {
		if (toolTip == null) {
			toolTip = new ShowAppToolTip();
			;
			// toolTip.getButton().addActionListener(toolTipBtnListener);
			toolTip.setComponent(this);
		}
		return toolTip;
	}

	/**
	 * 设置提示出现的位置
	 */
	public Point getToolTipLocation(MouseEvent event) {
		TreePath path = this.getClosestPathForLocation(event.getPoint().x,
				event.getPoint().y);
		Rectangle rect = this.getPathBounds(path);
		if (rect != null) {
			Point point = new Point(rect.x - 250, rect.y);
			return point;
		} else {
			return null;
		}

	}

	JPopupMenu popMenu;

	JMenuItem addItem;
	JMenuItem delItem;
	JMenuItem editItem;

	public void initMenu() {
		PopMenu pop = new PopMenu();
		popMenu = new JPopupMenu();
		addItem = new JMenuItem(strItemTitleAdd);
		addItem.addActionListener(pop);

		delItem = new JMenuItem(strItemTitleDel);
		delItem.addActionListener(pop);
		editItem = new JMenuItem(strItemTitleRename);
		editItem.addActionListener(pop);

		popMenu.add(addItem);
		popMenu.add(delItem);
		popMenu.add(editItem);

	}

	// 用于处理弹出菜单对应的事件.
	final class PopMenu implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {

			TreePath treepath = getSelectionPath();//获取选中节点
			// 下面两行取得选取节点的父节点.
			DefaultMutableTreeNode selectionNode = (DefaultMutableTreeNode) treepath
					.getLastPathComponent();
			TreeNode groupNode = (TreeNode) selectionNode.getParent();
			//获取组名groupNode.toString()
			
			
			JMenuItem item = (JMenuItem) e.getSource();
			String strFlag = item.getText();
		
		
			// -----------------------------------------------------------
			
			if (strFlag.equals(strItemTitleAdd)) {//添加
				addBookmark();
			} else if (strFlag.equals(strItemTitleDel)) {
				
				

	
				String[] options = { "确定(Y)", "取消(N)" };
				int result = JOptionPane.showOptionDialog(null, "您是否确定删除书签？",
						"删除书签", JOptionPane.DEFAULT_OPTION,
						JOptionPane.INFORMATION_MESSAGE, null, options,
						options[0]);
				options = null;
				if (result == JOptionPane.OK_OPTION) {// 确定操作
					
					DefaultMutableTreeNode note = (DefaultMutableTreeNode) getLastSelectedPathComponent();
					if (note.isLeaf()) {// 是否是叶子节点
						JLabel url = (JLabel) note.getUserObject();
						delBookmark(url.getName());
					} else {
						// 删除分组（未处理
					}
					// ---------------------------------------------------------
					DefaultMutableTreeNode parent = (DefaultMutableTreeNode) note
							.getParent();
					print(parent.getPath().toString());
					parent.remove(note);note = null;
					((DefaultTreeModel) getModel()).reload(parent);
					
//					JOptionPane.showMessageDialog(null, "删除成功！");
				}

				
			
				
			} else if (strFlag.equals(strItemTitleRename)) {

			} else if (strFlag.equals(strItemTitlMessagee)) {

			}
			
			

		}
		
		private boolean delBookmark(String url){
			if(control.delBookmark( url)){
				return true;
			}
			return false;
			
		}

		//添加书签
		void addBookmark() {
			 
			JTextField url=new JTextField();
			JTextField title=new JTextField();
			JTextField group=new JTextField();
			Object[] message={
				"请输入URL:",url,
				"请输入Title:",title,
				"请输入所属分组:",group,
			};
			String[] options={"确定(Y)","取消(N)"};
			int result = JOptionPane.showOptionDialog(
					null,
					message,
					"添加书签",
					JOptionPane.DEFAULT_OPTION,
					JOptionPane.INFORMATION_MESSAGE,
					null,
					options,
					options[0]
					);
			if (result == JOptionPane.OK_OPTION){
				//打开文件
				if(url!=null&&title!=null){
					logger.debug("对话狂的操作结果："+url.getText()+title.getText()+group.getText());
					logger.debug("control为："+control);
					if(control==null)control=new Control();
					control.addBookmark(url.getText(), title.getText(), group.getText());
				}
				
			}
				
			
		}


	}

	void print(String str) {
		logger.debug(str);
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		// -------------弹出的提示---------------------------------------
		int selRow = getRowForLocation(e.getX(), e.getY()); // 返回节点所在的行，-1表示鼠标定位不在显示的单元边界内
		TreePath selPath = getPathForLocation(e.getX(), e.getY()); // 返回指定节点的树路径

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		//print("" + this.visibleRowCount);
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		// -------------右键弹出菜单---------------------------------------
		int selRow = getRowForLocation(e.getX(), e.getY()); // 返回节点所在的行，-1表示鼠标定位不在显示的单元边界内
		boolean condition = true;
		condition = condition && (selRow != -1); // 如果选中
		condition = condition && (e.getClickCount() == 1); // 单击
		// 如果是右键点击
		if (condition == true && (e.getButton() == 3)) {
			popMenu.show(e.getComponent(), e.getX(), e.getY());
			// 选中节点
			TreePath path = getPathForLocation(e.getX(), e.getY());

			setSelectionPath(path);// 设置当前位置的节点为选中节点
		}

		// ----------------------------------------------------

		// 双击
		if (e.getClickCount() == 2) {

			TreePath treepath = getSelectionPath();
			// 下面两行取得选取节点的父节点.
			DefaultMutableTreeNode selectionNode = (DefaultMutableTreeNode) treepath
					.getLastPathComponent();
			TreeNode parent = (TreeNode) selectionNode.getParent();
			if (parent != null) {
				// 由DefaultTreeModel的removeNodeFromParent()方法删除节点，包含它的子节点。
				// treeModel.removeNodeFromParent(selectionNode);
				// 获得父节点的标题parent.toString()
				DefaultMutableTreeNode note = (DefaultMutableTreeNode) getLastSelectedPathComponent();

				if (note.isLeaf()) {// 是否是叶子节点
					JLabel jlab = (JLabel) note.getUserObject();
					URI uri = null;
					try {
						uri = new URI(jlab.getName());
						run.runURI(uri);
					} catch (URISyntaxException e1) {
						// TODO Auto-generated catch block
						print("打开URI出错！");
						e1.printStackTrace();
					}
					
				}
			}

		}

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseDragged(MouseEvent e) {
		// TODO Auto-generated method stub
		// 鼠标按键在组件上按下并拖动时调用。
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		// TODO Auto-generated method stub
		// 鼠标按键在组件上按下并拖动时调用。
		TreePath path = getPathForLocation(e.getX(), e.getY());
		if (path != null) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
					.getLastPathComponent();
			if (node.isLeaf()) {// 是否为叶子节点
				
				// 取得选取节点的父节点.
				TreeNode parent = (TreeNode) ((DefaultMutableTreeNode) path
						.getLastPathComponent()).getParent();
				
				JLabel jl = (JLabel) node.getUserObject();
				setToolTipText("<html><body>类别:"+parent.toString()
						+ "<br/>标题:" + jl.getText()
						+ "<br/>URL:" + jl.getName()
						+ "</body></html>");
			}
		} else {
			// 鼠标移出
		}

	}

}
